import time
import re
from common.pre_config_brower import chrome_brower, request_for_sales
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


class Next:
    def __init__(self, url):
        self.driver = chrome_brower(disableIMG=True)
        self.home_url = url
        self.main_windows_id = None
        self.open_web()

    # open the web pages
    def open_web(self):
        try:
            self.driver.get(self.home_url)
            self.main_windows_id = self.driver.window_handles[-1]
        except Exception as e:
            print("open the first page failure", e)

    # search the elements, e.g. production name , href, picture and so on
    def get_info_from_page(self):
        time.sleep(2)
        self.roll_to_top()
        time.sleep(2)

        get_all_items = self.driver.find_elements_by_css_selector(
            "[class='Item Fashion  ']")
        for item in get_all_items:
            produce_info = item.find_element_by_xpath(
                "section/div[@class = 'Info']/h2/a")
            produce_name = produce_info.get_attribute(
                'data-label')
            price_item = item.find_element_by_xpath(
                "section/div[@class = 'Info']/div[@class = 'Price']/a")
            price_value = price_item.text if price_item else "none"
            produce_url = produce_info.get_attribute('href')

            img_item = item.find_element_by_xpath(
                "./section/div[@class = 'Images']/a/img")

            img_info = img_item.get_attribute('src')
            jpg_url = img_item.get_attribute(
                'data-src') if "greyPlaceholder" in img_info else img_info
            print(produce_url, produce_name,
                  price_value, jpg_url.split("?X")[0])
            # if not jpg_url:
            #     jpg_url = img_obj.get_attribute('data-original')
            yield jpg_url, produce_name, price_value, produce_url

    def roll_to_top(self):
        js = "var q=document.documentElement.scrollTop=10000"
        self.driver.execute_script(js)

    def get_all_items(self):
        total_info = self.driver.find_element_by_id(
            "total-results-count").text
        total_num = re.findall(r"(\d+).*?Products", total_info)[0]
        print("total:", total_num)

        while True:
            for info in self.get_info_from_page():
                yield info
            next_page = self.driver.find_elements_by_css_selector(
                "[class='Page Next']")
            if next_page:
                self.home_url = next_page[0].get_attribute('href')
                self.open_web()
            else:
                break

        self.driver.close()
